using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 隐身Buff - 使目标对敌人不可见
/// </summary>
public class StealthBuff : BuffBase
{
    private bool m_OriginalVisibility;
    private float m_OriginalAlpha;
    private SpriteRenderer[] m_SpriteRenderers;
    private Color[] m_OriginalColors;

    public StealthBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
    }

    protected override void OnStart()
    {
        base.OnStart();
        
        // 获取所有SpriteRenderer组件
        m_SpriteRenderers = Target.GetComponentsInChildren<SpriteRenderer>();
        m_OriginalColors = new Color[m_SpriteRenderers.Length];
        
        // 保存原始颜色
        for (int i = 0; i < m_SpriteRenderers.Length; i++)
        {
            m_OriginalColors[i] = m_SpriteRenderers[i].color;
        }
        
        // 应用隐身效果
        ApplyStealthEffect();
        
        // 播放隐身特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        // 设置隐身状态
        Target.SetStealth(true);
        
        Logger.Log("StealthBuff", $"{Target.name} 进入隐身状态");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        // 隐身期间不需要特殊处理
    }

    private void ApplyStealthEffect()
    {
        // 降低透明度
        for (int i = 0; i < m_SpriteRenderers.Length; i++)
        {
            Color color = m_OriginalColors[i];
            color.a = 0.3f; // 设置为70%透明度
            m_SpriteRenderers[i].color = color;
        }
        
        // 禁用碰撞检测（可选）
        var colliders = Target.GetComponents<Collider2D>();
        foreach (var collider in colliders)
        {
            collider.enabled = false;
        }
    }

    private void RemoveStealthEffect()
    {
        // 恢复原始透明度
        for (int i = 0; i < m_SpriteRenderers.Length; i++)
        {
            m_SpriteRenderers[i].color = m_OriginalColors[i];
        }
        
        // 恢复碰撞检测
        var colliders = Target.GetComponents<Collider2D>();
        foreach (var collider in colliders)
        {
            collider.enabled = true;
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log("StealthBuff", $"{Target.name} 隐身效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        // 移除隐身效果
        RemoveStealthEffect();
        
        // 移除隐身状态
        Target.SetStealth(false);
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Stealth"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return false; // 隐身效果不能叠加，只能刷新持续时间
    }
}